export default {
	namespaced: true,
	state: {
		/**
		 * id: string
		 * image: string
		 * price: number
		 * count: number
		 * title: string
		 * word: string
		 * state: boolean
		*/ 
		carList: uni.getStorageSync('carList') || []
	},
	getters: {
		// 总数量
		totalCount(state) {
			return state.carList.reduce((p, n) => {
				return p + n.count
			}, 0)
		},
		// 总价计算
		totalPrice(state) {
			return state.carList.reduce((p,n) => {
				return n.state ? p + n.count * n.price : p
			}, 0)
		},
		// 选中状态
		totalState(state){
			return state.carList.every(v => v.state)
		}
		
	},
	mutations: {
		// 加入购物车
		addCarList(state, payload) {
			const item = state.carList.find(v => v.id === payload.id)
			if(item) item.count += payload.count || 1
			else state.carList.push(payload)
		},
		// 状态切换
		switchState(state, payload) {
			const item = state.carList.find(v => v.id === payload.id)
			if(item) item.state = !item.state
		},
		// 单选改变
		changeCount(state, payload) {
			const item = state.carList.find(v => v.id === payload.id)
			if(item) item.count = payload.count
		},
		// 全选改变
		switchTotalState(state, payload) {
			state.carList.forEach(v => v.state = payload)
		},
		// 删除操作
		deleteItem(state, payload) {
			state.carList = state.carList.filter(v => v.id !== payload.id)
		}
	}
}